<template>
  <div id="cesiumContainer">
    <div style="position:absolute;top:10px;left:10px;z-index:50">
      <!-- <v-btn type="primary" @click="drawArrow">箭头</v-btn>
      <v-btn id="pointBtn" @click="drawPoint">画点</v-btn>
      <v-btn id="lineBtn" @click="drawLine">画线</v-btn> -->
      <!-- <v-btn id="polyBtn" @click="polyBtn">画面</v-btn> -->
      <v-btn
        id="rectBtn"
        @click="rectBtn"
      >框选</v-btn>
      <!-- <v-btn id="circleBtn">画圆</v-btn> -->
      <v-btn
        id="clearBtn"
        @click="clearHandle"
      >清除</v-btn>
      <v-btn
        id="goBtn"
        @click="goBtn"
      >执行</v-btn>
      <v-btn
        id="testFun"
        @click="testFun1"
      >测试</v-btn>
      <!-- <prop-editor></prop-editor> -->
    </div>
    <div id="slider"></div>
  </div>
</template>
<script>
/* eslint-disable */
export default {
  name: "cesiumViewer",
  components: {
    // 'prop-editor': Cps.PropEditor
  },
  props: {},
  data () {
    return {
      cps: undefined,
      viewer: null,
      removeImageryLayers: [],
      graphList: [],
      pointList: [],
      imgtest: ''
    }
  },
  mounted () {
    var viewer = new this.Cesium.Viewer('cesiumContainer', {
      baseLayerPicker: false,
      terrainProvider: new this.Cesium.CesiumTerrainProvider({
        url: window.config.mapIP + '/DEM10',
        requestVertexNormals: true
      }),
      // imageryProvider: new this.Cesium.SingleTileImageryProvider({
      //   url: 'static/earth_base.jpg'
      // })
      imageryProvider: new this.Cesium.UrlTemplateImageryProvider({
        url: window.config.mapIP + '/world/{z}/{x}/{reverseY}.jpg',
        tilingScheme: new this.Cesium.GeographicTilingScheme({ ellipsoid: this.Cesium.Ellipsoid.WGS84 }),
        minimumLevel: 1,
        maximumLevel: 7
      })
    })
    // var layers = viewer.scene.imageryLayers
    //   layers.addImageryProvider(new this.Cesium.UrlTemplateImageryProvider({
    //       url : 'http://127.0.0.1:8080/china/{z}/{x}/{y}.png',
    //       maximumLevel : 12
    //   }))
    var layers = viewer.scene.imageryLayers
    layers.addImageryProvider(new this.Cesium.UrlTemplateImageryProvider({
      url: window.config.baseIP + '/tile/{z}/{y}/{x}',
      maximumLevel: 19
    }))
    viewer.camera.flyTo({
      destination: this.Cesium.Cartesian3.fromDegrees(117.769, 38.985, 15000.0)
    });

    this.viewer = viewer
    this.testFun(layers)
    // this.cps = new Cps(viewer, {})
    // 贴图
    // var redPolygon = view.entities.add({
    // name : 'Red polygon on surface',
    // polygon : {
    //         hierarchy : this.Cesium.Cartesian3.fromDegreesArray([125, 45,
    //                                                         125, 42,
    //                                                         128, 42,
    //                                                         128, 45]),
    //         material : 'static/SV1-01_MSS_0012_0538_20170106_L2A_0000000001.jpg'
    //     }
    // })
  },
  methods: {
    polyBtn () {
      let _this = this
      _this.drawPolygon(function (positions) {
        var wgs84Positions = []
        for (var i = 0; i < positions.length; i++) {
          var wgs84Point = _this.Cartesian3_to_WGS84({
            x: positions[i].x,
            y: positions[i].y,
            z: positions[i].z
          })
          wgs84Positions.push(wgs84Point)
        }
        console.log(wgs84Positions)
      })
    },
    rectBtn () {
      let _this = this
      _this.clearHandle()
      _this.drawRect(function (positions) {
        var wgs84_positions = [];
        for (var i = 0; i < positions.length; i++) {
          var wgs84_point = _this.Cartesian3_to_WGS84({
            x: positions[i].x,
            y: positions[i].y,
            z: positions[i].z
          });
          wgs84_positions.push(wgs84_point);
        }
        console.log(wgs84_positions);
        _this.pointList = wgs84_positions
      });
    },
    // 画面
    drawPolygon: function (callback) {
      var _this = this
      var PolygonPrimitive = (function () {
        function _ (positions) {
          this.options = {
            name: '多边形',
            polygon: {
              hierarchy: [],
              perPositionHeight: true,
              outline: true,
              outlineColor: _this.Cesium.Color.RED,
              material: _this.Cesium.Color.RED.withAlpha(0.2)
            }
          }
          this.hierarchy = positions
          this._init()
        }

        _.prototype._init = function () {
          var _self = this
          var _update = function () {
            return _self.hierarchy
          }
          // 实时更新polygon.hierarchy
          this.options.polygon.hierarchy = new _this.Cesium.CallbackProperty(_update, false)
          _this.viewer.entities.add(this.options)
        }
        return _
      })()

      var handler = new _this.Cesium.ScreenSpaceEventHandler(_this.viewer.scene.canvas)
      var positions = []
      // eslint-disable-next-line
      var poly = undefined

      // 鼠标单击画点
      handler.setInputAction(function (movement) {
        var cartesian = _this.viewer.scene.camera.pickEllipsoid(movement.position, _this.viewer.scene.globe.ellipsoid)
        if (positions.length === 0) {
          positions.push(cartesian.clone())
        }
        positions.push(cartesian)
      }, _this.Cesium.ScreenSpaceEventType.LEFT_CLICK)
      // 鼠标移动
      handler.setInputAction(function (movement) {
        var cartesian = _this.viewer.scene.camera.pickEllipsoid(movement.endPosition, _this.viewer.scene.globe.ellipsoid)
        if (positions.length >= 2) {
          if (!_this.Cesium.defined(poly)) {
            poly = new PolygonPrimitive(positions)
          } else {
            if (cartesian !== undefined) {
              positions.pop()
              cartesian.y += (1 + Math.random())
              positions.push(cartesian)
            }
          }
        }
      }, _this.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      // 鼠标右键单击结束绘制
      handler.setInputAction(function (movement) {
        handler.destroy()
        callback(positions)
      }, _this.Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    },
    //画矩形
    drawRect: function (callback) {
      let _self = this;
      let pointsArr = [];
      _self.shape = {
        points: [],
        rect: null,
        entity: null
      };
      var tempPosition;
      var handle = new _self.Cesium.ScreenSpaceEventHandler(_self.viewer.scene.canvas);
      //鼠标左键单击画点
      handle.setInputAction(function (click) {
        tempPosition = _self.getPointFromWindowPoint(click.position);
        //选择的点在球面上
        if (tempPosition) {
          if (_self.shape.points.length == 0) {
            pointsArr.push(tempPosition);
            _self.shape.points.push(_self.viewer.scene.globe.ellipsoid.cartesianToCartographic(tempPosition));
            _self.shape.rect = _self.Cesium.Rectangle.fromCartographicArray(_self.shape.points);
            _self.shape.rect.east += 0.000001;
            _self.shape.rect.north += 0.000001;
            _self.shape.entity = _self.viewer.entities.add({
              rectangle: {
                coordinates: _self.shape.rect,
                material: _self.Cesium.Color.RED.withAlpha(0.1),
                outline: true,
                outlineWidth: 2,
                outlineColor: _self.Cesium.Color.RED,
                height: 0
              }
            });
            _self.bufferEntity = _self.shape.entity;
          }
          else {
            handle.removeInputAction(_self.Cesium.ScreenSpaceEventType.MOUSE_MOVE);
            handle.removeInputAction(_self.Cesium.ScreenSpaceEventType.LEFT_CLICK);
            callback(pointsArr);
          }
        }
      }, _self.Cesium.ScreenSpaceEventType.LEFT_CLICK);
      //鼠标移动
      handle.setInputAction(function (movement) {
        if (_self.shape.points.length == 0) {
          return;
        }
        var moveEndPosition = _self.getPointFromWindowPoint(movement.endPosition);
        //选择的点在球面上
        if (moveEndPosition) {
          pointsArr[1] = moveEndPosition;
          _self.shape.points[1] = _self.viewer.scene.globe.ellipsoid.cartesianToCartographic(moveEndPosition);
          _self.shape.rect = _self.Cesium.Rectangle.fromCartographicArray(_self.shape.points);
          if (_self.shape.rect.west == _self.shape.rect.east)
            _self.shape.rect.east += 0.000001;
          if (_self.shape.rect.south == _self.shape.rect.north)
            _self.shape.rect.north += 0.000001;
          _self.shape.entity.rectangle.coordinates = _self.shape.rect;
        }
      }, _self.Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
    // 清除所有Entity和ImageryLayers
    clearHandle: function () {
      // 移除所有实体Entity
      this.viewer.entities.removeAll()
      // 移除cesium加载的ImageryLayer
      for (var i = 0; i < this.removeImageryLayers.length; i++) {
        this.viewer.imageryLayers.remove(this.removeImageryLayers[i])
      }
      this.viewer.dataSources.removeAll()
    },
    getPointFromWindowPoint (point) {
      if (this.viewer.scene.terrainProvider.constructor.name == "EllipsoidTerrainProvider") {
        return this.viewer.camera.pickEllipsoid(point, this.viewer.scene.globe.ellipsoid);
      } else {
        var ray = this.viewer.scene.camera.getPickRay(point);
        return this.viewer.scene.globe.pick(ray, this.viewer.scene);
      }
    },
    // 笛卡尔坐标系转WGS84坐标系
    Cartesian3_to_WGS84: function (point) {
      var cartesian33 = new this.Cesium.Cartesian3(point.x, point.y, point.z)
      var cartographic = this.Cesium.Cartographic.fromCartesian(cartesian33)
      var lat = this.Cesium.Math.toDegrees(cartographic.latitude)
      var lng = this.Cesium.Math.toDegrees(cartographic.longitude)
      var alt = cartographic.height
      return { lat: lat, lng: lng, alt: alt }
    },
    // WGS84坐标系转笛卡尔坐标系
    WGS84_to_Cartesian3: function (point) {
      var car33 = this.Cesium.Cartesian3.fromDegrees(point.lng, point.lat, point.alt)
      var x = car33.x
      var y = car33.y
      var z = car33.z
      return { x: x, y: y, z: z }
    },
    goBtn () {
      let _this = this
      console.log(_this.pointList)
      if (_this.$root.classification.indexOf("seg") != -1) {
        _this.axios({
          method: 'post',
          url: window.config.baseIP2 + '/image/imageSeg',
          responseType: 'arraybuffer',
          data: {
            pointList: _this.pointList
          }
        })
          .then(function (response) {
            console.log(response.data);
            let bytes = new Uint8Array(response.data);
            let data = "";
            let len = bytes.byteLength;
            for (let i = 0; i < len; i++) {
              data += String.fromCharCode(bytes[i]);
            }
            _this.imgtest = "data:image/png;base64," + window.btoa(data);
            _this.viewer.entities.add({
              polygon: {
                hierarchy: _this.Cesium.Cartesian3.fromDegreesArray([_this.pointList[0].lng, _this.pointList[0].lat,
                _this.pointList[0].lng, _this.pointList[1].lat, _this.pointList[1].lng, _this.pointList[1].lat, _this.pointList[1].lng, _this.pointList[0].lat]),
                material: _this.imgtest
              },
            })
            // let jsonData = JSON.parse(response.data)
            // console.log(jsonData);
          })
      } else if (_this.$root.classification.indexOf("detect") != -1) {
        _this.axios({
          method: 'post',
          url: window.config.baseIP2 + '/image/detectImage',
          data: {
            pointList: _this.pointList
          }
        })
          .then(function (response) {
            console.log(response.data);
            _this.viewer.dataSources.add(_this.Cesium.GeoJsonDataSource.load(response.data, {
              stroke: _this.Cesium.Color.HOTPINK,
              fill: _this.Cesium.Color.PINK,
              strokeWidth: 3,
              markerSymbol: '?'
            }));
            // let jsonData = JSON.parse(response.data)
            // console.log(jsonData);
          })
      } else {
        _this.axios({
          method: 'post',
          url: window.config.baseIP2 + '/image/recognition',
          params: {
            classification: _this.$root.classification
          },
          data: {
            pointList: _this.pointList
          }
        })
          .then(function (response) {
            console.log(response.data);
            // let jsonData = JSON.parse(response.data)
            // console.log(jsonData);
            _this.viewer.dataSources.add(_this.Cesium.GeoJsonDataSource.load(response.data, {
              stroke: _this.Cesium.Color.HOTPINK,
              fill: _this.Cesium.Color.PINK,
              strokeWidth: 3,
              markerSymbol: '?'
            }));
          })
          .catch(function (error) {
            console.log(error);
          });
      }

    },
    testFun (layers) {
      let _this = this
      layers.addImageryProvider(new this.Cesium.UrlTemplateImageryProvider({
        url: window.config.baseIP + '/tile2/{z}/{y}/{x}',
        maximumLevel: 19
      }));
      var detectImg = layers.addImageryProvider(new this.Cesium.UrlTemplateImageryProvider({
        url: window.config.baseIP + '/tile1/{z}/{y}/{x}',
        maximumLevel: 19
      }));
      detectImg.splitDirection = this.Cesium.ImagerySplitDirection.LEFT;
      // Sync the position of the slider with the split position
      var slider = document.getElementById("slider");
      _this.viewer.scene.imagerySplitPosition =
        slider.offsetLeft / slider.parentElement.offsetWidth;

      var handler = new this.Cesium.ScreenSpaceEventHandler(slider);

      var moveActive = false;

      function move (movement) {
        if (!moveActive) {
          return;
        }

        var relativeOffset = movement.endPosition.x;
        var splitPosition =
          (slider.offsetLeft + relativeOffset) /
          slider.parentElement.offsetWidth;
        slider.style.left = 100.0 * splitPosition + "%";
        _this.viewer.scene.imagerySplitPosition = splitPosition;
      }

      handler.setInputAction(function () {
        moveActive = true;
      }, this.Cesium.ScreenSpaceEventType.LEFT_DOWN);
      handler.setInputAction(function () {
        moveActive = true;
      }, this.Cesium.ScreenSpaceEventType.PINCH_START);

      handler.setInputAction(move, this.Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      handler.setInputAction(move, this.Cesium.ScreenSpaceEventType.PINCH_MOVE);

      handler.setInputAction(function () {
        moveActive = false;
      }, this.Cesium.ScreenSpaceEventType.LEFT_UP);
      handler.setInputAction(function () {
        moveActive = false;
      }, this.Cesium.ScreenSpaceEventType.PINCH_END);
    },
    testFun1 () {
      let _this = this

      _this.viewer.camera.flyTo({
        destination: this.Cesium.Cartesian3.fromDegrees(-122.461, 37.787, 10000.0)
      });
      if (document.getElementById("slider").style.display == "inline") {
        document.getElementById("slider").style.display = "none";
      } else {
        document.getElementById("slider").style.display = "inline";
      }
    }
  }
}
</script>
<style>
#cesiumContainer {
  width: 100%;
  height: 100%;
}
#slider {
  position: absolute;
  left: 50%;
  top: 0px;
  background-color: #d3d3d3;
  width: 5px;
  height: 100%;
  z-index: 9999;
  display: none;
}

#slider:hover {
  cursor: ew-resize;
}
</style>
